<template>
	<view class="container">
		<!-- 头部导航 -->
		<!-- <view class="header-bag">
			<image :src="serverAddress + 'img/icon-Get-into@3.png'" class="back" @click="goBack"></image>
			<text class="page-title font18">填写云主资料</text>
		</view> -->

		<view class="wrapper">
			<!-- 身份信息表单 -->
			<view class="identity font14">
				<!-- 姓名 -->
				<view class="person-info displayflexL">
					<view class="displayflexL">
						<text class="required">*</text>
						<text>姓　　名:</text>
					</view>
					<view>
						<input type="text" class="name" v-model="formData.realname" :disabled="true"
							placeholder="请输入姓名" />
					</view>
				</view>

				<!-- 性别 -->
				<view class="person-info displayflexL">
					<view class="displayflexL">
						<text class="required">*</text>
						<text>性　　别:</text>
					</view>
					<view class="displayflexL">
						<view class="gender-option" @click="selectGender(1)">
							<image
								:src="serverAddress + (formData.sex === 1 ? 'img/radio-checked.png' : 'img/radio.png')"
								class="radio-icon"></image>
							<text class="gender-text">男</text>
						</view>
						<view class="gender-option" @click="selectGender(2)">
							<image
								:src="serverAddress + (formData.sex === 2 ? 'img/radio-checked.png' : 'img/radio.png')"
								class="radio-icon"></image>
							<text class="gender-text">女</text>
						</view>
					</view>
				</view>

				<!-- 身份证号 -->
				<view class="person-info displayflexL" style="border-bottom: none;">
					<view class="displayflexL">
						<text class="required">*</text>
						<text>身份证号:</text>
					</view>
					<view>
						<input type="text" class="sfz-num" v-model="formData.id_number" :disabled="true"
							placeholder="请输入身份证号" />
					</view>
				</view>
			</view>

			<!-- 身份证照片上传 -->
			<view class="id-card">
				<view class="displayflexL">
					<text class="required">*</text>
					<text>手持身份证拍照</text>
				</view>
				<view class="displayflex" style="margin-top: 0.3rem;">
					<!-- 身份证正面 -->
					<view class="photo-box" @click="chooseImage('front')">
						<image
							:src="idCardImages.front ? (baseUrl + idCardImages.front) : (serverAddress + 'img/icon-sfz(zheng)@2x.png')"
							class="id-card-img"></image>
						<text>身份证正面</text>
					</view>
					<!-- 身份证反面 -->
					<view class="photo-box" @click="chooseImage('back')">
						<image
							:src="idCardImages.back ? (baseUrl + idCardImages.back) : (serverAddress + 'img/icon-sfz(fan)@2x.png')"
							class="id-card-img"></image>
						<text>身份证反面</text>
					</view>
				</view>
			</view>

			<!-- 协议同意 -->
			<view class="id-card">
				<view class="yuedu" @click="toggleAgree">
					<image :src="serverAddress + (agreeProtocol ? 'img/login/icon-dui.png' : 'img/check.png')"
						class="check-icon"></image>
					<text class="agree">我已阅读并同意</text>
					<text class="protocol-link" @click.stop="viewProtocol">《优享优品平台云主协议》</text>
				</view>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-btn font17" @click="submitForm">提交</view>
		</view>

		<!-- 选择图片弹窗 -->
		<view v-if="showImagePicker" class="mask" @click="hideImagePicker">
			<view class="choose-icon font15" @click.stop="">
				<view @click="selectFromAlbum">选择图像</view>
				<view @click="hideImagePicker">取消</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		identityApi
	} from '@/api/index.js'
	import {
		inject
	} from 'vue'
	export default {
		data() {
			return {
				baseUrl: inject('$baseUrl'),
				serverAddress: inject('$serverAddress', ''),
				formData: {
					realname: '',
					sex: '',
					id_number: ''
				},
				idCardImages: {
					front: '',
					back: ''
				},
				agreeProtocol: false,
				showImagePicker: false,
				currentImageType: '',
				editId: '' // 编辑时的ID
			}
		},

		onLoad(options) {
			if (options.id) {
				this.editId = options.id
				this.loadEditData()
			} else {
				this.loadIdentityInfo()
			}
		},

		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 加载身份信息
			async loadIdentityInfo() {
				try {
					const res = await identityApi.getIdentityInfo()
					if (res.r === 0 && res.data) {
						this.formData.realname = res.data.realname || ''
						this.formData.id_number = res.data.id_number || ''
					}
				} catch (error) {
					console.error('获取身份信息失败:', error)
				}
			},

			// 加载编辑数据
			async loadEditData() {
				try {
					const res = await identityApi.getStaffApplyList({
						id: this.editId
					})
					if (res.r === 0 && res.data.st && res.data.st.length > 0) {
						const data = res.data.st[0]
						this.formData.realname = data.realname
						this.formData.sex = data.sex
						this.formData.id_number = data.id_number

						// 加载图片
						if (data.imgs && data.imgs.length > 0) {
							data.imgs.forEach(img => {
								if (img.img_type === 1) {
									this.idCardImages.front = img.file_path
								} else {
									this.idCardImages.back = img.file_path
								}
							})
						}
					}
				} catch (error) {
					console.error('获取编辑数据失败:', error)
					uni.showToast({
						title: '获取数据失败',
						icon: 'none'
					})
				}
			},

			// 选择性别
			selectGender(sex) {
				this.formData.sex = sex
			},

			// 选择图片
			chooseImage(type) {
				this.currentImageType = type
				this.showImagePicker = true
			},

			// 从相册选择
			selectFromAlbum() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.uploadImage(res.tempFilePaths[0])
					}
				})
				this.hideImagePicker()
			},

			// 隐藏图片选择器
			hideImagePicker() {
				this.showImagePicker = false
			},

			// 上传图片
			async uploadImage(filePath) {
				uni.showLoading({
					title: '上传中...'
				})

				try {
					const uploadRes = await this.uploadFile(filePath)
					if (uploadRes && uploadRes !== 'error') {
						this.idCardImages[this.currentImageType] = uploadRes
					}
				} catch (error) {
					console.error('上传失败:', error)
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 文件上传方法
			uploadFile(filePath) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.baseUrl + 'home/Upload/upload_img_wx', // 替换为实际的上传接口
						filePath: filePath,
						name: 'file',
						success: (res) => {
							try {
								const data = JSON.parse(res.data)
								if (data.r === 0) {
									resolve(data.data.file_path)
								} else {
									reject(new Error(data.msg || '上传失败'))
								}
							} catch (e) {
								reject(new Error('解析响应失败'))
							}
						},
						fail: (error) => {
							reject(error)
						}
					})
				})
			},

			// 切换协议同意状态
			toggleAgree() {
				this.agreeProtocol = !this.agreeProtocol
			},

			// 查看协议
			viewProtocol() {
				uni.setStorageSync('current_tag', 'yg_xy')
				uni.navigateTo({
					url: '/pages/identity/agreement?tag=yg_xy'
				})
			},

			// 表单验证
			validateForm() {
				if (!this.formData.sex) {
					uni.showToast({
						title: '请选择性别',
						icon: 'none'
					})
					return false
				}

				if (!this.idCardImages.front) {
					uni.showToast({
						title: '请上传身份证正面照',
						icon: 'none'
					})
					return false
				}

				if (!this.idCardImages.back) {
					uni.showToast({
						title: '请上传身份证背面照',
						icon: 'none'
					})
					return false
				}

				if (!this.agreeProtocol) {
					uni.showToast({
						title: '请同意优享优品平台云主协议',
						icon: 'none'
					})
					return false
				}

				return true
			},

			// 提交表单
			async submitForm() {
				if (!this.validateForm()) {
					return
				}

				uni.showLoading({
					title: '提交中...'
				})

				try {
					const submitData = {
						realname: this.formData.realname,
						sex: this.formData.sex,
						id_number: this.formData.id_number,
						cfi_path: this.idCardImages.front,
						cbi_path: this.idCardImages.back
					}

					let res
					if (this.editId) {
						// 更新申请
						submitData.id = this.editId
						res = await identityApi.updateStaffApply(submitData)
					} else {
						// 新增申请
						res = await identityApi.addStaffApply(submitData)
					}

					if (res.r === 0) {
						uni.showToast({
							title: res.msg || '提交成功',
							icon: 'success'
						})

						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/identity/goumayunzhu' + (res.data ? '?id=' + res.data :
									'')
							})
						}, 1500)
					} else {
						uni.showToast({
							title: res.msg || '提交失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('提交失败:', error)
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background: #eeeeee;
		min-height: 100vh;
	}

	.header-bag {
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		height: 88rpx;
		background: #fff;
		border-bottom: 1px solid #e3e3e3;

		.back {
			position: absolute;
			left: 30rpx;
			width: 40rpx;
			height: 40rpx;
		}

		.page-title {
			font-size: 36rpx;
			color: #333;
		}
	}

	.wrapper {
		padding-bottom: 100rpx;
	}

	.identity {
		width: 100%;
		border-top: 1px solid #e3e3e3;
		background: white;
		margin-top: 20rpx;

		.person-info {
			border-bottom: 1px solid #e3e3e3;
			height: 90rpx;
			line-height: 90rpx;
			width: 690rpx;
			margin: 0 auto;
			position: relative;

			>view:nth-child(1) {
				width: 25%;
			}

			>view:nth-child(2) {
				width: 75%;
			}

			input {
				width: 460rpx;
				line-height: 80rpx;
				margin-left: 20rpx;
				color: gray;
				background: #ffffff;
				font-size: 25rpx;
			}
		}
	}

	.required {
		color: #ff5033;
		margin: 5rpx 8rpx 0 0;
		font-size: 30rpx;
	}

	.gender-option {
		display: flex;
		align-items: center;
		margin-left: 30rpx;

		.radio-icon {
			width: 22rpx;
			height: 22rpx;
			margin-right: 12rpx;
		}

		.gender-text {
			font-size: 28rpx;
		}
	}

	.id-card {
		font-size: 30rpx;
		margin-top: 20rpx;
		padding: 30rpx;
		background: white;

		.id-card-img {
			width: 305rpx;
			height: 193rpx;
		}

		text {
			font-size: 26rpx;
			text-align: center;
			display: block;
			margin-top: 10rpx;
		}
	}

	.photo-box {
		position: relative;
		width: 305rpx;
		height: 220rpx;
		margin-right: 20rpx;
	}

	.yuedu {
		font-size: 24rpx;
		color: #8d8d8d;
		display: flex;
		align-items: center;

		.check-icon {
			width: 25rpx;
			height: 25rpx;
			margin-right: 5rpx;
		}

		.protocol-link {
			color: #11b445;
		}
	}

	.submit-btn {
		height: 90rpx;
		width: 689rpx;
		line-height: 90rpx;
		text-align: center;
		background: #ff5033;
		color: white;
		margin: 40rpx auto;
		border-radius: 20rpx;
		font-size: 34rpx;
	}

	.mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 999;
		display: flex;
		align-items: flex-end;
	}

	.choose-icon {
		width: 100%;
		background: white;
		border-radius: 20rpx 20rpx 0 0;

		>view {
			height: 100rpx;
			line-height: 100rpx;
			text-align: center;
			border-bottom: 1px solid #eee;
			font-size: 30rpx;

			&:last-child {
				border-bottom: none;
			}
		}
	}

	.displayflexL {
		display: flex;
		align-items: center;
	}

	.displayflex {
		display: flex;
	}

	.font14 {
		font-size: 28rpx;
	}

	.font17 {
		font-size: 34rpx;
	}

	.font18 {
		font-size: 36rpx;
	}
</style>